package com.totoro.controller;

import com.fasterxml.jackson.databind.JsonNode;
import com.totoro.pojo.*;
import com.totoro.service.*;
import com.totoro.utils.ReturnFormat;
import lombok.SneakyThrows;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.*;

/**
 * @author TOTORO
 * @date 2021/7/28 1:31
 * 提供管理前端的所有接口
 */
@RestController
@CrossOrigin(origins = "http://localhost:8088", allowCredentials = "true")
@RequestMapping("/tmallAdmin")
public class AdminController {
    private final AdminService adminService;
    private final StatisticsService statisticsService;
    private final CategoryService categoryService;
    final
    UserService userService;
    private final IndexService indexService;

    Map<String, PhoneCode> codeMap = new HashMap<>();

    public AdminController(AdminService adminService, StatisticsService statisticsService, CategoryService categoryService, UserService userService, IndexService indexService) {
        this.adminService = adminService;
        this.statisticsService = statisticsService;
        this.categoryService = categoryService;
        this.userService = userService;
        this.indexService = indexService;
    }

    public Map<String, PhoneCode> getCodeMap() {
        return codeMap;
    }


    /**
     * 获取所有首页分类Json
     * @return
     */
    @RequestMapping("/getIndexCategoryJson")
    public String getIndexCategoryJson(){

        // 先获取一级分类
        List<IndexCategory> oneCategory = indexService.findAllOneCategory();
        oneCategory.forEach(v->{
            List<IndexCategory> twoCategory = indexService.findAllTwoCategoryByOneCategoryId(v.getId());
            v.setIndexCategoryList(twoCategory);
            // 循环三级
            twoCategory.forEach(tc ->{
                List<IndexCategory> threeCategory = indexService.findAllThreeCategoryByTwoCategoryId(tc.getId());
                tc.setIndexCategoryList(threeCategory);
            });
        });
        return ReturnFormat.retData(oneCategory, true);
    }

    @RequestMapping("/getAllTwoCategory")
    public String getAllTwoCategory(){
        return ReturnFormat.retData(categoryService.findAllTwoCategory(), true);
    }


    /**
     * 使用密码进行登录
     * @param jsonNode
     * @return
     */
    @SneakyThrows
    @RequestMapping(value = "/passwordLogin", method = RequestMethod.POST)
    public String adminPasswordLogin(@RequestBody JsonNode jsonNode){
        String account = jsonNode.get("account").asText();
        String password = jsonNode.get("password").asText();
        // 查询是否有该管理员
        Admin admin = adminService.findAdminByPasswordAndPhone(account, null);
        if(null == admin){
            return ReturnFormat.retData("用户不存在", false);
        } else if(admin.getAdminPassword().equals(password)){
            // login success
            admin.setAdminPassword(null);
            return ReturnFormat.retData(admin, true);
        } else{
            return ReturnFormat.retData("密码错误", false);
        }
    }

    /**
     * 发送一条效验码
     * @param jsonNode
     * @return
     */
    @RequestMapping(value = "/sendCode", method = RequestMethod.POST)
    public String sendCode(@RequestBody JsonNode jsonNode){
        String phone = jsonNode.get("phone").asText();
        // 先查询手机是否存在
        Admin admin = adminService.findAdminByPasswordAndPhone(null, phone);
        if(null == admin){
            return ReturnFormat.retData("没有绑定该手机号码的管理员！", false);
        }
        // 发送一条手机验证码
        Integer code = new Random().nextInt(899999)+100000;
        //String msg = PhoneUtil.getPhoneCode(phone, phoneCode);
        PhoneCode phoneCode = new PhoneCode(phone,code,new Date());
        if(codeMap.containsKey(phone)){
            codeMap.replace(phone, phoneCode);
        } else{
            codeMap.put(phone,phoneCode);
        }
        return ReturnFormat.retData(phoneCode, true);
    }

    /**
     * 使用手机+验证码进行登录
     * @param jsonNode
     * @return
     */
    @RequestMapping(value = "/phoneLogin", method = RequestMethod.POST)
    public String adminPhoneLogin(@RequestBody JsonNode jsonNode){
        String phone = jsonNode.get("phone").asText();
        Integer code = jsonNode.get("code").asInt();
        // 进行map的比对
        boolean isHavePhone = false;

        if(!codeMap.containsKey(phone)){
            return ReturnFormat.retData("验证码已失效，请重新获取", false);
        }
        if(!codeMap.get(phone).getCode().equals(code)){
            return ReturnFormat.retData("验证码输入错误，请重新尝试", false);
        }
        Admin admin = adminService.findAdminByPasswordAndPhone(null, phone);
        if(null == admin){
            return ReturnFormat.retData("系统繁忙，请稍后再试", false);
        }
        codeMap.remove(phone);
        return ReturnFormat.retData(admin, true);
    }

    /** 以下为第一个路由: 首页数据总览接口 -------------------------------------------------------*/

    /**
     * 获得周用户峰值
     * @return
     */
    @RequestMapping(value = "/getUserOnline", method = RequestMethod.POST)
    public String getUserOnline(){
        List<UserOnline> userOnlines = statisticsService.findDayUserOnline();
        if(null == userOnlines || userOnlines.size()<=0){
            return ReturnFormat.retData("系统繁忙，请稍后再试", false);
        }
        return ReturnFormat.retData(userOnlines, true);
    }

    /**
     * 返回最火分类
     * @return
     */
    @RequestMapping(value = "/getCategoryDate", method = RequestMethod.POST)
    public String getCategoryDate(){
        List<Category> categories = statisticsService.findHotCategoryByBuyCount();
        if(null == categories || categories.size()<=0) {
            return ReturnFormat.retData("系统繁忙，请稍后再试", false);
        }
            return ReturnFormat.retData(categories, true);
    }

    /**
     * 获得某个类别下的最火商品排名
     * @param jsonNode
     * @return
     */
    @RequestMapping(value = "/getHotCategoryProduct", method = RequestMethod.POST)
    public String getHotCategoryProduct(@RequestBody JsonNode jsonNode){
        String cname = jsonNode.get("cname").asText();
        List<Product> products = statisticsService.findHotCategoryProduct(cname);
        if(null == products || products.size()<=0) {
            return ReturnFormat.retData("系统繁忙，请稍后再试", false);
        }
        return ReturnFormat.retData(products, true);
    }

    /**
     * 获得交易额
     * @return
     */
    @RequestMapping(value = "/getSales", method = RequestMethod.POST)
    public String getSales(){
        Statistics sc = statisticsService.findAllPriceAndNowPrice();
        if(null == sc){
            return ReturnFormat.retData("系统繁忙，请稍后再试", false);
        }
        return ReturnFormat.retData(sc, true);
    }

    @RequestMapping(value = "/getSellerCount", method = RequestMethod.POST)
    public String getSellerCount(){
        Integer allSellerCount = statisticsService.findAllSellerCount();
        Integer weekSellerCount = statisticsService.findWeekSellerCount();
        List<Integer> list = new ArrayList<>();
        list.add(allSellerCount);
        list.add(weekSellerCount);
        return ReturnFormat.retData(list, true);
    }

    /** 用户操作 */

    /**
     * 获得用户
     * @param jsonNode
     * @return
     */
    @RequestMapping(value = "/getUserList", method = RequestMethod.POST)
    public String findAllUser(@RequestBody JsonNode jsonNode){
        Integer page = jsonNode.get("params").get("page").asInt();
        String nameFilter = jsonNode.get("params").get("name").asText();
        Integer isBan = jsonNode.get("params").get("isBan").asInt();
        Integer sellerStatus = jsonNode.get("params").get("sellerStatus").asInt();
        Statistics statistics = new Statistics();
        statistics.setUserPage(page);
        statistics.setUserName(nameFilter);
        statistics.setIsBan(isBan);
        statistics.setSellerStatus(sellerStatus);
        List<User> users = statisticsService.findUserByPageAndName(statistics);
        if(null == users || users.size()<=0) {
            return ReturnFormat.retData("系统繁忙，请稍后再试", false);
        }
        int totalPage = (users.size() + 20 -1) / 20;
        List<Object> list = new ArrayList<>();
        list.add(users);
        list.add(totalPage);
        return ReturnFormat.retData(list, true);
    }

    @RequestMapping(value = "/banUser", method = RequestMethod.POST)
    @ResponseBody
    public String banUser(@RequestBody JsonNode jsonNode){
        JsonNode root = jsonNode.get("params");
        int uid = root.get("uid").asInt();
        System.out.println(uid);
        userService.deleteUser(uid);
        return ReturnFormat.retData("封禁成功", true);
    }

    @RequestMapping(value = "/untieBanUser", method = RequestMethod.POST)
    @ResponseBody
    public String untieBanUser(@RequestBody JsonNode jsonNode){
        JsonNode root = jsonNode.get("params");
        int uid = root.get("uid").asInt();
        userService.untieUserBan(uid);
        return ReturnFormat.retData("封禁成功", true);
    }

    /**
     * 同意申请卖家
     * @param jsonNode
     * @return
     */
    @RequestMapping(value = "/confirmApplySeller", method = RequestMethod.POST)
    public String confirmApplySeller(@RequestBody JsonNode jsonNode){
        int uid = jsonNode.get("uid").asInt();
        String shopName = jsonNode.get("shopName").asText();
        // 同意申请
        adminService.updateUserApplySeller(uid, 1);
        // 修改为卖家
        adminService.updateUserIsSeller(uid);
        // 新增卖家
        Seller seller = new Seller();
        seller.setUid(uid);
        adminService.addSeller(seller);
        // 新增店铺
        adminService.addShop(shopName, seller.getId());
        return ReturnFormat.retData("success", true);
    }

    /**
     * 拒绝买家的申请
     * @param jsonNode
     * @return
     */
    @RequestMapping(value = "/refuseApplySeller", method = RequestMethod.POST)
    public String refuseApplySeller(@RequestBody JsonNode jsonNode){
        int uid = jsonNode.get("uid").asInt();
        // 拒绝
        adminService.updateUserApplySeller(uid, 2);
        return ReturnFormat.retData("success", true);
    }

    /**
     * 查找所有轮播图
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/findAllCarrouselImage", method = RequestMethod.POST)
    public String findAllCarrouselImage(HttpServletRequest request){
        String uploadPath = request.getSession().getServletContext().getRealPath("/")+"static\\img\\index\\carousel\\";
        String[] strings = new File(uploadPath).list();
        return ReturnFormat.retData(strings, true);
    }


    /**
     * 上传一张轮播图
     * @param file
     * @param request
     * @return
     */
    @SneakyThrows
    @ResponseBody
    @RequestMapping(value = "/uploadRevolvingLanternImage", method = RequestMethod.POST)
    public String uploadRevolvingLanternImage(@RequestParam("file") MultipartFile file, HttpServletRequest request){
        String fileName = file.getOriginalFilename();
        String imagePath = request.getSession().getServletContext().getRealPath("/")+"static\\img\\index\\carousel\\"+fileName;
        File file2 = new File(imagePath);
        if(file2.exists()){
            return ReturnFormat.retData("该轮播图已存在，请选择其他图片", false);
        }
        file.transferTo(file2);
        return ReturnFormat.retData("上传成功", true);
    }

    /**
     * 删除一张轮播图
     * @param jsonNode
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/deleteRevolvingLanternImage", method = RequestMethod.POST)
    public String deleteRevolvingLanternImage(@RequestBody JsonNode jsonNode, HttpServletRequest request){
        String fileName = jsonNode.get("fileName").asText();
        String imagePath = request.getSession().getServletContext().getRealPath("/")+"static\\img\\index\\carousel\\"+fileName;
        File file = new File(imagePath);
        if(file.exists()){
            file.delete();
        }
        return ReturnFormat.retData("删除成功", true);
    }

    @RequestMapping(value = "/editIndexCategory", method = RequestMethod.POST)
    public String editIndexCategory(@RequestBody JsonNode jsonNode){
        int icId = jsonNode.get("id").asInt();
        int categoryId = jsonNode.get("cid").asInt();
        String categoryName = jsonNode.get("categoryName").asText();
        String categorySearchKeyword = jsonNode.get("categorySearchKeyword").asText();
        IndexCategory indexCategory = new IndexCategory(icId, categoryName, categorySearchKeyword, categoryId, null, null);
        indexService.updateCategoryDetail(indexCategory);
        return ReturnFormat.retData("修改成功", true);
    }




}
